﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace eLearning.Pages.PanelUtilities
{
    public class ButtonEvent : Button
    {
        public Panel ParentPanel { get; set; }
        public bool AutoHide { get; set; }

        public ButtonEvent()
        {
            this.Loaded += new RoutedEventHandler(ButtonEvent_Loaded);
            this.Click += new RoutedEventHandler(ButtonEvent_Click);
            this.AutoHide = true;
        }

        public static T FindParent<T>(UIElement control) where T : UIElement
        {
            UIElement p = VisualTreeHelper.GetParent(control) as UIElement;
            if (p != null)
            {
                if (p is T)
                {
                    //loai bo Title Bar khoi cac ket qua tim thay va tra ve parent cua title bar
                    if (p is TitleBar) return FindParent<T>(p);
                    return p as T;
                }
                return FindParent<T>(p);
            }
            return null;
        }

        protected virtual void ButtonEvent_Click(object sender, RoutedEventArgs e){}

        protected virtual void ButtonEvent_Loaded(object sender, RoutedEventArgs e)
        {
            this.ApplyTemplate();
            if (AutoHide) this.Visibility = Visibility.Collapsed;

            Panel p = FindParent<Panel>(this);
            if (p != null)
            {
                ParentPanel = p;
                p.MouseEnter += new MouseEventHandler(Panel_MouseEnter);
                p.MouseLeave += new MouseEventHandler(Panel_MouseLeave);
            }
        }
        
        void Panel_MouseEnter(object sender, RoutedEventArgs e)
        {if (AutoHide) this.Visibility = Visibility.Visible;}

        void Panel_MouseLeave(object sender, RoutedEventArgs e)
        {if (AutoHide) this.Visibility = Visibility.Collapsed;}
    }
}
